"""
从账号状态查询
手工同步
"""

from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
import time
import logging.config
from conf import settings
from lib.common import wait_table, host_row_search, return_page

logging.config.dictConfig(settings.LOGGING_DIC)  # 导入上面定义的logging配置
logger1 = logging.getLogger("从账号查询")
logger2 = logging.getLogger("手工同步")


def account_query_interface(browser, wait, host_row, host):
    if host_row is None or host.is_bad:
        logger1.error(f"主机 {host.ip} 存在问题,中止从账号查询")
        return
    # 从账号查询
    # host_row.click()
    browser.find_element(By.XPATH, '//*[@id="viewAcct"]').click()

    # 等待加载
    wait_table(browser)
    # 输入账号查询
    browser.find_element(By.XPATH, '//*[@id="acctName"]').send_keys(host.account)
    browser.find_element(By.XPATH, '//*[@id="searchButton"]').click()
    # 等待加载
    wait_table(browser)

    text_list = []
    try:
        for i in range(1, 150):
            text_list.clear()
            account_row = browser.find_element(
                By.XPATH, f'/html/body/div[1]/div/div/span[1]/div/div/div/div/div[3]/div[3]/div/table/tbody/tr[{i}]'
            )
            for text in account_row.text.split(" "):
                text_list.append(text)

            print(i, text_list)

            if text_list[0] == host.account:  # 如果账号存在
                host.account_status = text_list[1] + " " + text_list[3]  # 记录账号状态 是否加锁+账号类型
                if not (text_list[1] == "正常" and (text_list[3] == '管理帐号' or text_list[3] == '普通帐号')):
                    print(text_list[3])
                    print(type(text_list[3]))
                    logger1.error(f'主机{host} 从账号存在问题')
                    host.is_bad = True
                print("查询到该用户")
                host.save()
                return_page(browser, wait)
                return True
    except NoSuchElementException as e:
        if i == 11:
            host.account_status = "此页可能没有该主机NoSuchElement"
            logger1.warning(f"主机 {host.ip} 用户{host.account}: 此页可能没有此用户NoSuchElement")
            host.is_bad = True
            print("查询结束，此页可能没有此用户")
            return True
        else:
            host.account_status = "没有此用户NoSuchElement"
            if host.is_manual_sync:
                host.is_bad = True
            logger1.error(f"主机 {host.ip}  用户{host.account}: 没有此用户NoSuchElement")
    host.save()
    return_page(browser, wait)
    return False


def manual_sync_interface(browser, wait, host):
    host_row = host_row_search(browser, host)
    host_row.click()
    browser.find_element(By.XPATH, '//*[@id="manualSync"]').click()

    for i in range(6, 1000):
        try:
            if browser.find_element(By.XPATH, f'/html/body/div[{i}]').is_displayed():
                browser.find_element(By.XPATH, f'/html/body/div[{i}]/div[11]/button[2]/span').click()

                browser.switch_to.frame(1)
                for t in range(1000):
                    time.sleep(0.2)
                    text = wait.until(EC.presence_of_element_located((
                        By.XPATH, '/html/body/div[1]/div/div/div/div'
                    ))).text
                    if "手工同步成功" in text:
                        print(text)
                        logger2.info(f"主机 {host.ip}: 手工同步成功")
                        break
                    if "手工同步失败" in text:
                        print(text)
                        host.sync_status = "同步失败"
                        host.is_bad = True
                        logger2.error(f"主机 {host.ip}: 手工同步失败")
                        break
                browser.switch_to.parent_frame()
                browser.find_element(By.XPATH, f'/html/body/div[{i + 1}]/div[1]/a').click()
                break
        except NoSuchElementException as e:
            pass
    host.is_manual_sync = True
    # host_row.click()
    account_query_interface(browser, wait, host_row, host)


def only_manual_sync_interface(browser, wait, host):
    host_row = host_row_search(browser, host)

    if host_row is None:
        logger2.error(f"主机 {host.ip} 不存在,中止手工同步")
        return

    if host.sync_status not in ["正常", "同步失败"]:
        host.sync_status += ' 不能同步'
        host.save()
        return

    host_row.click()
    browser.find_element(By.XPATH, '//*[@id="manualSync"]').click()

    for i in range(6, 5000):
        try:
            if browser.find_element(By.XPATH, f'/html/body/div[{i}]').is_displayed():
                browser.find_element(By.XPATH, f'/html/body/div[{i}]/div[11]/button[2]/span').click()
                browser.switch_to.frame(1)

                browser.switch_to.parent_frame()
                browser.find_element(By.XPATH, f'/html/body/div[{i + 1}]/div[1]/a').click()
                host.sync_status = '已自动同步'
                host.save()
                break
        except NoSuchElementException as e:
            pass
